const { User, Friend_Group } = require('../model')
const jwt = require('../utils/jwt')
const { jwtSecret } = require('../config')
const utils = require('../utils')
const { formatTime } = require('../utils/date')
const Error = require('../config/error-code')
const config = require('../config')
const path = require('path')
const fs = require('fs')
const secret = require('../utils/secret')

exports.login = async (req, res, next) => {
    try {
        const user = req.user.toJSON()
        const token = await jwt.sign({
            id: user._id
        }, jwtSecret, {
            expiresIn: 60 * 60 *12
        })
        delete user.password
        res.status(200).json({
            success:true,
            errcode:"",
            errmsg:"",
            data:{
                msg:'登录成功',
                content:{
                    ...user,
                    token
                }
            }
        })
    } catch (err) {
        next(err)
    }
}

exports.register = async (req, res, next) => {
    try {
        let user = new User(req.body)
        user.username = utils.randomUsername(8,1)
        user.password = secret.md5Encode(secret.Decrypt(req.body.registerPassword))
        await user.save()
        user = user.toJSON()
        delete user.registerPassword
        delete user.password
        const count = await User.countDocuments();
        res.status(200).json({
            success:true,
            errcode:"",
            errmsg:"",
            data:{
                msg:'注册成功',
                count,
                content:user
            }
        })
    } catch (err) {
        next(err)
    }
}

exports.forgetUser = async (req, res, next) => {
    try
    {
        let username = req.user.username
        let md5Password = secret.md5Encode(secret.Decrypt(username))
        await User.updateOne({ username }, { password:md5Password, updatedAt:formatTime() })
        res.status(200).json({
            success:true,
            errcode:'',
            errmsg:'',
            data:{
                content:username
            }
        })
    }
    catch (err)
    {
        next(err)
    }
}

exports.check = async (req,res,next) => {
    try {
        let user = req.user;
        if (!user.isEnable)
        {
            return res.status(200).json({
                success:false,
                errcode:Error['XP025'].errcode,
                errmsg:Error['XP025'].errmsg,
                data:{
                }
            })
        }
        res.status(200).json({
            success:true,
            errcode:"",
            errmsg:"",
            data:{
                msg:'验证成功',
                content:user
            }
        })
    } catch (err) {
        next(err)
    }
}
